package com.zmzncs.lmtc.common.websocket;

import com.zmzncs.lmtc.common.util.DateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

@Component
@Slf4j
public class WebsocketUtil {

    @Autowired
    @Lazy
    WebsocketUtil websocketUtil;

    /**
     * 异步发送消息
     * @param customerId    客户id
     * @param message   消息内容
     */
    @Async
    public void sendMessage(String customerId, String message) {
        List<WebsocketServer> websocketServerList = WebsocketServer.webSocketSet.get(customerId);

        try {
            //  睡眠3秒，等待数据库数据提交
            Thread.sleep(3000);

            if(websocketServerList != null && websocketServerList.size() > 0){
                for(WebsocketServer websocketServer: websocketServerList){
                    log.info("发送消息-向客户【{}】发送消息：【{}】", customerId + WebsocketServer.separator + websocketServer.session.getId(), message);
                    websocketServer.session.getBasicRemote().sendText(message);
                    //  存储消息，客户回复消息后清除，1分钟过期
                    WebsocketServer.messageMap.put(message, DateTimeUtil.getCurrAfterMinuteDate(new Date(), 1));

                    //  检查客户端是否接受到数据，如果没有则重新发送
                    websocketUtil.checkReply(websocketServer, customerId, message);
                }
            } else {
                log.info("发送消息-客户【{}】未在线", customerId);
            }
        } catch (Exception e) {
            log.error("发送消息-客户【{}】发送消息异常，异常信息【{}】", customerId, e.getMessage());
            e.printStackTrace();
        }
        //this.session.getAsyncRemote().sendText(message);
    }

    /**
     * 检查回复的消息。如果客户端没有收到消息，则重新发送
     */
    @Async
    public void checkReply(WebsocketServer websocketServer, String customerId,  String message) {
        try {
            //  睡眠2秒
            Thread.sleep(2000);

            boolean flag = true;
            while(flag) {
                if(WebsocketServer.messageMap.get(message) != null){
                    log.info("发送消息-向客户【{}】发送消息：【{}】", customerId + WebsocketServer.separator + websocketServer.session.getId(), message);
                    websocketServer.session.getBasicRemote().sendText(message);
                    //  存储消息，客户回复消息后清除，1分钟过期
                    WebsocketServer.messageMap.put(message, DateTimeUtil.getCurrAfterMinuteDate(new Date(), 1));
                } else {
                    log.info("客户【{}】收到消息【{}】", customerId + WebsocketServer.separator + websocketServer.session.getId(), message);
                    flag = false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}